package com.project.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionPress implements HttpSessionListener {
    //创建session时触发
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("创建session");
        //得到上下文对象
        ServletContext context = se.getSession().getServletContext();
        //取出在线人数
        int number = (Integer)context.getAttribute("number");
        //将在线人数加一
        context.setAttribute("number", number+1);
    }

    //销毁session时触发
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("销毁session");
        //得到上下文对象
        ServletContext context = se.getSession().getServletContext();
        //取出在线人数
        int number = (Integer)context.getAttribute("number");
        //将在线人数加一
        context.setAttribute("number", number-1);
    }
}
